<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\common\model\users;

use app\command\extend\http\ApiCache;
use app\common\model\base\A3Mall;
use mall\library\Huobi;
use think\facade\Cache;
use think\facade\Log;

class UsersKey extends A3Mall {

    protected $autoWriteTimestamp = true;
    protected $name = "users_key";
    protected $type = [
        "id"=>"integer",
        "platform"=>"integer",
        "account_id"=>"integer",
        "user_id"=>"integer",
        "access_key"=>"string",
        "secret_key"=>"string",
        "create_time"=>"integer",
        "update_time"=>"integer",
    ];

    /**
     * 通过用户 ID 获取用户绑定数据
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function findOne($userId) {
        $result = $this->where(['user_id'=>$userId])->select();
        return  $result?$result->toArray():[];
    }

    //获取火币账户id
    public function getAccountId($accesKey=null,$secretKey=null) {
        $req = new Huobi(true, $accesKey,$secretKey);
        $accountInfo = $req->get_account_accounts();
        if($accountInfo && $accountInfo['status'] == 'error') {
            return false;
        } else {
            return isset($accountInfo['data'][0]['id'])?$accountInfo['data'][0]['id']:false;
        }
    }

    //获取交易对
    public function getMarketTickers($cache=false) {
        $marketTickers = Cache::store('redis')->get('market_tickers');
        if($marketTickers) {
            return $marketTickers;
        } else {
            $req = new Huobi();
            $marketTickersTmp = $req->get_market_tickers();
            if($marketTickersTmp && $marketTickersTmp['status'] == 'ok') {
                $marketTickers = array_column($marketTickersTmp['data'],null,'symbol');
                if($cache) {
                    Cache::store('redis')->set('market_tickers',$marketTickers,3);
                }
                return $marketTickers;
            }
        }
    }

    //获取账户余额
    public function getAccountBalance($userKeyInfo = [],$cache=false) {
        if(empty($userKeyInfo)) {
            return 0;
        }

        /****** 通过火币中间系统获取余额 ******/
        if(array_key_exists('id',$userKeyInfo) && ($accountBalance = ApiCache::request('GetBalance',[
                'user_id' => $userKeyInfo['id'],
                'account_id'    => $userKeyInfo['account_id'],
                'access_key'    => $userKeyInfo['access_key'],
                'secret_key'    => $userKeyInfo['secret_key'],
            ]))) {
            return sprintf('%.4f',$accountBalance);
        }
        /**** END 通过火币中间系统获取余额 ****/

        $accountBalance = Cache::store('redis')->get('account_balance'.'_'.$userKeyInfo['account_id']);
        if($accountBalance) {
            return $accountBalance;
        } else {
            if(empty($userKeyInfo)) {
                return sprintf('%.4f',0);
            }
            $req = new Huobi($userKeyInfo['account_id'],$userKeyInfo['access_key'],$userKeyInfo['secret_key']);
            $accountBalanceTmp = $req->get_account_balance($userKeyInfo['account_id']);
            if($accountBalanceTmp && $accountBalanceTmp['status'] == 'ok') {
                $balance = 0;
                foreach ($accountBalanceTmp['data']['list'] as $val) {
                    if($val['currency']=='usdt' && $val['type']=='trade') {
                        $balance = $val['balance'];
                    }
                }
                $accountBalance = sprintf('%.4f',$balance);
                if($cache) {
                    Cache::store('redis')->set('account_balance'.'_'.$userKeyInfo['account_id'],$accountBalance,5);
                }
                return $accountBalance;
            }
        }
    }

}
